<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客登陆页</title>

    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/login.css">

</head>

<body>
    <div class="nav">
        <img src="pic/logo2.jpg" alt="">
        <span class="blog-title">我的博客系统</span>
        <div class="space"></div>
        <a class="nav-span" href="blog_list.html"></a>
        <a class="nav-span" href="blog_edit.html"></a>
    </div>
    
    <div class="container-login">
        <div class="login-dialog">
            <h3>登陆</h3>
            <div class="row">
                <span>用户名</span>
                <input type="text" name="username" id="username">
            </div>
            <div class="row">
                <span>密码</span>
                <input type="password" name="password" id="password">
            </div>
            <div class="row">
                <button id="submit" onclick="login()">提交</button>
            </div>

        </div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script>
        function login() {
    var username = $("#username").val();
    var password = $("#password").val();
    
    // 前端基础验证（可选，提供即时反馈）
    if (!username.trim()) {
        alert("用户名不能为空");
        return;
    }
    if (!password.trim()) {
        alert("密码不能为空");
        return;
    }
    if (username.length > 20) {
        alert("用户名不能大于20位");
        return;
    }
    if (password.length > 20) {
        alert("密码不能超过20位");
        return;
    }

    $.ajax({
        type: "post",
        url: "/user/login",
        contentType: "application/json",
        data: JSON.stringify({
            "userName": username,
            "password": password
        }),
        success: function(result) { 
            if (result.code == 200 && result.data != null) {
                var response = result.data;
                localStorage.setItem("user_token", response.token);
                localStorage.setItem("loginUserId", response.userId);
                location.assign("blog_list.html");
            } else {
                alert(result.errMsg || "登录失败");
                return;
            }
        },
        error: function(xhr, status, error) {
            try {
                var errorResponse = JSON.parse(xhr.responseText);
                alert(errorResponse.errMsg || "请求失败");
            } catch (e) {
                alert("网络请求失败，请稍后重试");
            }
        }
    });
}

    </script>
</body>

</html>